<template>
  <el-card style="margin-bottom:20px;">
    <div slot="header" class="clearfix">
      <span>About me</span>
    </div>

    <div class="user-profile">
      <div class="box-center">
        <pan-thumb :image="user.avatar" :height="'100px'" :width="'100px'" :hoverable="false">
          <div>Hello</div>
          {{ user.role }}
        </pan-thumb>
      </div>
      <div class="box-center">
        <div class="user-name text-center">{{ user.name }}</div>
        <div class="user-role text-center text-muted">{{ user.role | uppercaseFirst }}</div>
      </div>
    </div>

    <!-- 修改头像和保存按钮区域 -->
    <div style="text-align:center; margin-top: 20px;">
      <el-button size="small" style="margin-bottom: 10px;" @click="openAvatarDialog">选择头像</el-button>
      <br>
      <el-button type="primary" :loading="loading" @click="saveProfile">保存</el-button>
    </div>

    <!-- 头像选择弹窗 -->
    <el-dialog title="选择头像" :visible.sync="dialogVisible">
      <div class="avatar-list">
        <img
          v-for="url in avatarLibrary"
          :key="url"
          :src="url"
          class="avatar-select-item"
          :class="{ selected: url === user.avatar }"
          loading="lazy"
          @click="chooseAvatar(url)"
          @error="handleAvatarError"
        >
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="loadAvatarLibrary">换一批</el-button>
        <el-button @click="dialogVisible = false">取消</el-button>
      </span>
    </el-dialog>
  </el-card>
</template>

<script>
import PanThumb from '@/components/PanThumb'

export default {
  components: { PanThumb },
  filters: {
    uppercaseFirst(value) {
      if (!value) return ''
      return value.charAt(0).toUpperCase() + value.slice(1)
    }
  },
  props: {
    user: {
      type: Object,
      default: () => ({
        name: '',
        email: '',
        avatar: '',
        role: ''
      })
    }
  },
  data() {
    return {
      dialogVisible: false,
      avatarLibrary: [],
      selectedAvatar: '',
      avatarCountPerStyle: 5,
      avatarStylesPerLoad: 10,
      avatarStyles: [
        'adventurer', 'adventurer-neutral', 'avataaars', 'avataaars-neutral',
        'big-ears', 'big-ears-neutral', 'big-smile', 'bottts', 'bottts-neutral',
        'croodles', 'croodles-neutral', 'fun-emoji', 'icons', 'identicon',
        'initials', 'lorelei', 'lorelei-neutral', 'micah', 'miniavs', 'notionists',
        'notionists-neutral', 'open-peeps', 'personas', 'pixel-art',
        'pixel-art-neutral', 'rings', 'shapes', 'thumbs'
      ],
      loading: false
    }
  },
  methods: {
    loadAvatarLibrary() {
      const avatars = []
      const shuffledStyles = [...this.avatarStyles].sort(() => 0.5 - Math.random())
      const selectedStyles = shuffledStyles.slice(0, this.avatarStylesPerLoad)

      for (const style of selectedStyles) {
        const seeds = Array.from({ length: this.avatarCountPerStyle }, () => 'user' + Math.floor(Math.random() * 10000))
        for (const seed of seeds) {
          avatars.push(`https://api.dicebear.com/9.x/${style}/svg?seed=${seed}`)
        }
      }

      this.avatarLibrary = avatars
      this.selectedAvatar = this.user.avatar || (avatars.length > 0 ? avatars[0] : '')
    },
    openAvatarDialog() {
      this.loadAvatarLibrary()
      this.dialogVisible = true
    },
    chooseAvatar(url) {
      this.user.avatar = url
      this.dialogVisible = false
    },
    saveSelectedAvatar() {
      this.user.avatar = this.selectedAvatar
      this.dialogVisible = false
    },
    handleAvatarError(event) {
      event.target.src = 'https://via.placeholder.com/60x60?text=?'
    },
    async saveProfile() {
      if (!this.user.avatar) {
        this.$message.warning('请选择头像后再保存')
        return
      }

      try {
        await this.$confirm('确定要保存这个头像吗？', '确认保存', {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning'
        })

        this.loading = true

        this.$store.dispatch('user/upAvatar', {
          username: this.user.name,
          avatar: this.user.avatar
        })
          .then(() => {
            this.$message.success('头像保存成功')
            this.$emit('avatar-saved', this.user.avatar)
          })
          .catch((error) => {
            this.$message.error('头像保存失败')
            console.error(error)
          })
          .finally(() => {
            this.loading = false
          })
      } catch (error) {
        // confirm 被取消或出错
        this.$message.info('已取消保存')
      }
    }

  }
}
</script>

<style lang="scss">
.box-center {
  margin: 0 auto;
  display: table;
}

.text-muted {
  color: #777;
}

.user-profile {
  .user-name {
    font-weight: bold;
  }

  .box-center {
    padding-top: 10px;
  }

  .user-role {
    padding-top: 10px;
    font-weight: 400;
    font-size: 14px;
  }
}

.el-dialog {
  width: 98%;
  max-width: 400px;
}

.avatar-list {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  max-height: 300px;
  overflow-y: auto;
  justify-content: flex-start;
}

.avatar-select-item {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  cursor: pointer;
  border: 2px solid transparent;
  transition: border-color 0.3s;
}

.avatar-select-item:hover {
  border-color: #409EFF;
}

.avatar-select-item.selected {
  border-color: #409EFF;
}
</style>
